<template>
    <view class="page-wrap">
        <view>
            <view class="info">
                <image class="cover" :src="info.cover"></image>
                <view class="right">
                    <view class="title text-cut">{{info.title}}</view>
                    <view class="price">
                        <text class="original" v-if="info.originalPrice">￥{{info.originalPrice}}</text>
                        <text class="sell">￥{{info.sellPrice}}</text>
                    </view>
                </view>
            </view>
            <u-form :model="form" ref="uForm" label-width="6em">
                <u-form-item border-bottom label="优惠券" prop="coupons" @click="couponShow = !disabled">
                    <u-input :placeholder="disabled? '无' : '请选择优惠券'" :value="payCouponAmount" disabled
                        input-align="right" color="#F44336" />
                    <CouponModuleUsable target-type="VOUCHER" :show="couponShow" :max="totalAmount" :def="form.coupons"
                        @close="couponShow = false" @confirm="handleCoupon" />
                    <u-icon slot="right" name="arrow-right" />
                </u-form-item>

                <u-form-item v-if="form.payTime" border-bottom label="支付时间" prop="payTime">
                    <u-input disabled placeholder="" input-align="right" v-model="form.payTime" />
                </u-form-item>
                <u-form-item v-if="form.offsetTime" border-bottom label="使用时间" prop="offsetTime">
                    <u-input disabled placeholder="" input-align="right" v-model="form.offsetTime" />
                </u-form-item>
            </u-form>
            <view class="qrcode" v-if="info.payStatus == 'PAYED'">
                <canvas id="qrcode" canvas-id="qrcode"></canvas>
                <cover-image v-if="info.offseted != 0" src="../../static/utils/used.png" class="used"></cover-image>
                <view class="text">{{qrcode}}</view>
            </view>
        </view>
        <footer-wrap>
            <view class="footer">
                <view v-if="disabled && form.payStatus == 'WAIT'" class="amount pay-cancel" @click="handleCancel">
                    取消订单
                </view>
                <view v-else class="amount">
                    <view>
                        合计：
                        <text class="pay-amount" v-if="disabled">￥{{form.payAmount}}</text>
                        <text class="pay-amount" v-else>￥{{(totalAmount - couponAmount).toFixed(2)}}</text>
                    </view>
                    <view class="coupon" v-if="payCouponAmount">
                        已减：<text>￥{{payCouponAmount}}</text>
                    </view>
                </view>
                <view class="action">
                    <u-button v-if="!disabled" shape="circle" type="primary" size="large"
                        @click="handleSave">立即支付</u-button>
                    <u-button v-else-if="form.payStatus == 'WAIT'" shape="circle" type="primary" size="large"
                        @click="handlePay">继续支付 ￥{{form.payAmount}}</u-button>
                    <view v-else class="pay-status">
                        <text class="cancel" v-if="form.payStatus == 'CANCELED'">{{form.payStatusName}}</text>
                        <text v-else-if="form.offseted == 0" class="unuse">待使用</text>
                        <text v-else class="used">已使用</text>
                    </view>
                </view>
            </view>
        </footer-wrap>
    </view>
</template>

<script>
    import {
        mapState,
        mapMutations
    } from 'vuex';
    import CouponModuleUsable from '@/pages/coupon/moduleUsable.vue'
    import UQRCode from '@/uni_modules/Sansnn-uQRCode/js_sdk/uqrcode/uqrcode.js';
    export default {
        components: {
            CouponModuleUsable
        },
        data() {
            return {
                id: '',
                info: {},
                form: {
                    id: '',
                    voucherId: '',
                    payStatus: '',
                    payTime: '',
                    offseted: '',
                    useTime: '',
                    coupons: [],
                },
                couponShow: false,
                couponAmount: 0,
                qrcode: '',
            };
        },
        computed: {
            ...mapState(['login']),
            totalAmount() {
                return this.info.sellPrice;
            },
            disabled() {
                return this.form.payStatus;
            },
            payCouponAmount() {
                let amount
                if (this.disabled) {
                    amount = this.form.totalAmount - this.form.payAmount;
                } else {
                    amount = this.couponAmount;
                }
                return amount || '';
            }
        },
        onLoad(option) {
            if (option.id) {
                this.$api.voucher.detail({
                    id: option.id
                }).then(res => {
                    this.info = res.info;
                    this.form.voucherId = this.info.id;
                })
            } else {
                this.$api.voucher.orderDetail({
                    id: option.orderId
                }).then(res => {
                    this.info = res.info
                    this.form = res.info
                    this.qrcode = res.qrcode;
                    this.drawQrcode()
                })
            }
        },
        methods: {
            handleCoupon(list, couponAmount) {
                console.log('handleCoupon', arguments)
                this.couponShow = false;
                this.couponAmount = couponAmount;
                this.form.coupons = list;
            },
            handleSave() {
                this.$api.voucher.createOrder(this.form).then(res => {
                    this.form.id = res.info
                    this.handlePay();
                })
            },
            handlePay() {
                let id = this.form.id;
                this.$api.voucher.wechatPay({
                    id
                }).then(res => {
                    if (res.payed) {
                        this.handleRefresh(id);
                        return;
                    }
                    uni.getProvider({
                        service: 'payment',
                        success: ({
                            service,
                            provider
                        }) => {
                            console.log('getProvider', arguments);
                            uni.requestPayment({
                                provider: provider[0],
                                ...res.params,
                                success: res => {
                                    this.handleRefresh(id);
                                },
                                fail: err => {
                                    uni.showModal({
                                        title: '支付失败',
                                        showCancel: false,
                                        complete: () => {
                                            this.$toPage({
                                                type: 'redirect',
                                                url: '/pages/voucher/add?orderId=' + id
                                            });
                                        }
                                    })
                                }
                            });
                        }
                    });
                });
            },
            handleRefresh(orderId) {
                this.$api.voucher.refresh({
                    orderId
                }).then(res => {
                    if (res.success) {
                        uni.showToast({
                            title: '支付成功!'
                        });
                    } else {
                        uni.showToast({
                            title: '支付完成!'
                        });
                    }
                    setTimeout(() => {
                        this.$toPage({
                            type: 'back'
                        });
                    }, 2000);
                })
            },
            handleCancel() {
                uni.showModal({
                    title: '提示',
                    content: '确定要取消该订单吗？',
                    success: (res) => {
                        if (!res.confirm) {
                            return;
                        }
                        this.$api.voucher.cancel({
                            orderId: this.form.id
                        }).then(res => {
                            uni.showModal({
                                title: '订单取消成功',
                                showCancel: false,
                                complete: () => {
                                    this.$toPage({
                                        type: 'back'
                                    });
                                }
                            })
                        });
                    }
                });
            },
            drawQrcode() {
                var qr = new UQRCode();
                if (this.form.offseted == 1) {
                    qr.foregroundColor = '#cdcdcd'
                }
                // 设置二维码内容
                qr.data = this.qrcode;
                // 设置二维码大小，必须与canvas设置的宽高一致
                qr.size = uni.upx2px(300);
                // 调用制作二维码方法
                qr.make();
                // 获取canvas上下文
                var canvasContext = uni.createCanvasContext('qrcode', this); // 如果是组件，this必须传入
                // 设置uQRCode实例的canvas上下文
                qr.canvasContext = canvasContext;
                // 调用绘制方法将二维码图案绘制到canvas上
                qr.drawCanvas();
            }
        },
    }
</script>

<style scoped lang="scss">
    $color-money: #F44336;

    .page-wrap {
        background: #fff;
        padding: 0 32rpx;

        .info {
            display: flex;
            margin-top: 32rpx;
            padding-bottom: 32rpx;
            border-bottom: solid 1rpx #eee;

            &+.info {}

            .cover {
                width: 200rpx;
                height: 128rpx;
                margin-right: 32rpx;
            }

            .right {
                flex: 1;
                min-width: 0;

                .title {
                    color: #333;
                    font-size: 32rpx;
                    font-weight: bold;
                }

                .price {
                    color: $color-money;
                    text-align: right;

                    .original {
                        font-size: 24rpx;
                        text-decoration: line-through;
                    }

                    .sell {
                        font-size: 32rpx;
                    }
                }
            }
        }

        .qrcode {
            position: relative;
            margin-top: 100rpx;

            canvas {
                width: 300rpx;
                height: 300rpx;
                display: block;
                margin: 0 auto;
            }

            .used {
                position: absolute;
                left: 220rpx;
                top: 50rpx;
                width: 246rpx;
                height: 200rpx;
                z-index: 999;
            }

            .text {
                padding-top: 18rpx;
                text-align: center;
            }
        }

        .footer {
            display: flex;
            align-items: center;
            padding: 32rpx;

            .amount {
                flex-grow: 1;

                .pay-amount {
                    font-size: 1.5em;
                    color: $color-money;
                }

                .coupon {
                    font-size: 0.7em;

                    text {
                        color: $color-money;
                    }
                }
            }

            .action {
                width: 300rpx;

                .pay-status {
                    color: $primary-color;
                    font-size: 38rpx;
                    text-align: right;

                    .used {
                        color: $success-color;
                    }

                    .used {
                        color: $success-color
                    }

                    .cancel {
                        color: $warning-color;
                    }
                }
            }

            .pay-cancel+.action {
                width: 500rpx;
            }
        }
    }
</style>